<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="物资类型" prop="id">
        <treeselect
          v-model="queryParams.id"
          :options="configOptions"
          placeholder="请选择类型"
          :normalizer="normalizer"
          :searchable="false"
          :appendToBody="true"
        />
      </el-form-item>
      <el-form-item label="所属仓库" prop="depotId">
        <el-select
          v-model="queryParams.depotId"
          placeholder="请选择所属仓库"
          clearable
          size="small"
        >
          <el-option
            v-for="depot in depotOptions"
            :key="depot.id"
            :label="depot.name"
            :value="depot.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="货位编号" prop="goodsCode">
        <el-input
          v-model="queryParams.goodsCode"
          placeholder="请输入货位"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编码" prop="pCode">
        <el-input
          v-model="queryParams.pCode"
          placeholder="请输入品名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入品名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格" prop="productmodel">
        <el-input
          v-model="queryParams.productmodel"
          placeholder="请输入品名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8"
      style="padding-top: 0 !important; margin: -6px 0 0 -6px !important"
    >
      <el-col v-if="isShow">
        <StrokeItem3
          title="种类"
          :number="infoData.typeNum || 0"
          unit="种"
          style="
            float: left;
            margin-bottom: 10px;
            width: 270px;
            margin-left: 0px;
          "
        />
        <StrokeItem3
          title="库存数量"
          :number="infoData.stockNum || 0"
          style="
            float: left;
            margin-bottom: 10px;
            width: 270px;
            margin-left: 10px;
          "
        />
        <StrokeItem3
          title="总额"
          :number="infoData.stockMoney || 0"
          unit="元"
          style="
            float: left;
            margin-bottom: 10px;
            width: 300px;
            margin-left: 10px;
          "
        />
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['equipment:stock:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment:stock:edit']"
          >修改</el-button
        >
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['equipment:stock:remove']">删除</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['equipment:stock:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="stockList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      max-height="550"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="货位" align="center" prop="goodsSpaceName" />
      <el-table-column
        label="编码"
        align="center"
        prop="basicProductInfo.code"
      />
      <el-table-column label="品名" align="center" prop="productName" />
      <el-table-column label="所属仓库" align="center" prop="depotName" />
      <el-table-column
        label="规格"
        align="center"
        prop="basicProductInfo.model"
        minWidth="140px"
      />
      <el-table-column
        label="类型"
        align="center"
        prop="basicProductInfo.typeName"
      />
      <el-table-column label="库存量" align="center" prop="inventory" />
      <el-table-column label="可用库存" align="center" prop="availableStock" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column
        label="单价（元）"
        align="center"
        prop="basicProductInfo.price"
        width="100"
      />
      <el-table-column
        label="总价（元）"
        align="center"
        prop="basicProductInfo.price"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.basicProductInfo.price > 0
              ? (
                  scope.row.basicProductInfo.price * scope.row.inventory
                ).toFixed(2)
              : "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equipment:stock:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['equipment:stock:remove']"
            v-if="scope.row.inventory == 0"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存管理对话框 -->
    <el-dialog
      v-myFullscreen
      :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body
      v-myDialogDrag
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="库位" prop="depotId">
              <el-input
                v-model="form.depotName"
                placeholder="请输入库位"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货位" prop="goodsSpaceId">
              <el-input
                v-model="form.goodsSpaceName"
                placeholder="请输入货位"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编码" prop="productId">
              <el-input
                v-model="form.code"
                placeholder="请输入品名"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品名" prop="productId">
              <el-input
                v-model="form.productName"
                placeholder="请输入品名"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="规格" prop="productId">
              <el-input
                v-model="form.model"
                placeholder="请输入品名"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="basicProductInfo.typeName">
              <el-input
                v-model="
                  form.basicProductInfo == null
                    ? null
                    : form.basicProductInfo.typeName
                "
                placeholder="请输入品名"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input
                v-model="form.unit"
                placeholder="请输入单位"
                :disabled="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存量" prop="inventory">
              <el-input
                v-model="form.inventory"
                placeholder="请输入库存量"
                :disabled="openDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可用库存" prop="availableStock">
              <el-input
                v-model="form.availableStock"
                placeholder="请输入可用库存"
                :disabled="openDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价(元）" prop="price">
              <el-input v-model="form.price" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总价（元）" prop="sum">
              <el-input v-model="form.sum" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
                :disabled="openDisabled"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!openDisabled">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStock,
  getStock,
  delStock,
  addStock,
  updateStock,
} from "@/api/equipment/materials/stock";
import { listDepot, getDepot } from "@/api/equipment/materials/depot";
import { treeselect } from "@/api/equipment/materials/productConfig";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import StrokeItem3 from "@/components/myComponents/stroke/item3.vue";
import { productStock } from "@/api/produce/index.js";
export default {
  name: "Stock",
  components: {
    Treeselect,
    StrokeItem3,
  },
  data() {
    return {
      //弹窗是否禁止编辑
      openDisabled: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存管理表格数据
      stockList: [],
      // 所属仓库
      depotOptions: [],
      configOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        depotId: null,
        goodsSpaceId: null,
        goodsCode: null,
        pCode: null,
        productName: null,
        inventory: null,
        availableStock: null,
        unit: null,
        id: null,
        productmodel: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //统计信息
      infoData: {
        stockMoney: 0,
        stockNum: 0,
        typeNum: 0,
      },
      //是否显示统计信息
      isShow: false,
    };
  },
  created() {
    this.getList();
    this.getDepot();
    this.getTreeselect();
    this.productStock();
    if (this.$route.query.show) {
      this.isShow = true;
    } else {
      this.isShow = false;
    }
  },
  activated() {
    // console.log(this.$route.query)
    if (this.$route.query.show) {
      //    console.log(11)
      this.isShow = true;
    } else {
      //     console.log(22)
      this.isShow = false;
    }
  },
  watch: {
    // 监听deptId
    "queryParams.depotId": "handleQuery",
    "queryParams.goodsCode": "handleQuery",
    "queryParams.pCode": "handleQuery",
    "queryParams.productName": "handleQuery",
    "queryParams.id": "handleQuery",
    "queryParams.productmodel": "handleQuery",
  },
  methods: {
    getDepot() {
      this.loading = true;
      let dParams = {
        type: "01",
      };
      listDepot(dParams).then((response) => {
        this.depotOptions = response.data;
        this.loading = false;
      });
    },
    //获取统计信息数据
    productStock() {
      let obj = {};
      obj.depotId = this.queryParams.depotId;
      obj.typeId = this.queryParams.id;
      productStock(obj).then((response) => {
        // console.log(response);
        if (response.code == 200) {
          this.infoData = response.data;
        }
      });
    },
    /** 查询库存管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      // if (null != this.queryParams.productName && " " != this.queryParams.productName) {
      //     this.queryParams.params["name"] = this.queryParams.productName;
      // };
      if (null != this.queryParams.pCode && " " != this.queryParams.pCode) {
        this.queryParams.params["code"] = this.queryParams.pCode;
      }
      listStock(this.queryParams).then((response) => {
        this.stockList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        depotId: null,
        goodsSpaceId: null,
        productId: null,
        inventory: null,
        availableStock: null,
        unit: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        remark: null,
        price: null,
        sum: null,
        code: null,
        model: null,
        basicProductInfo: {},
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.productStock();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.productStock();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.openDisabled = false;
      this.open = true;
      this.title = "添加库存管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.openDisabled = false;
      const id = row.id || this.ids;
      getStock(id).then((response) => {
        this.form = response.data;
        this.form.price = this.form.basicProductInfo.price;
        this.form.sum = (this.form.price * this.form.inventory).toFixed(2);
        this.form.code = this.form.basicProductInfo.code;
        this.form.model = this.form.basicProductInfo.model;
        this.open = true;
        this.title = "修改库存管理";
      });
    },
    /** 查看按钮 */
    handleView(row) {
      this.reset();
      this.openDisabled = true;
      const id = row.id || this.ids;
      getStock(id).then((response) => {
        this.form = response.data;
        this.form.price = this.form.basicProductInfo.price;
        this.form.sum = (this.form.price * this.form.inventory).toFixed(2);
        this.form.code = this.form.basicProductInfo.code;
        this.form.model = this.form.basicProductInfo.model;
        this.open = true;
        this.title = "查看库存管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateStock(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const rLoading = this.openLoading();
            addStock(this.form)
              .then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                rLoading.close();
                this.getList();
              })
              .catch((error) => {
                rLoading.close();
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除库存管理编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delStock(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "equipment/stock/export",
        {
          ...this.queryParams,
        },
        "库存管理" + this.parseTime(new Date()) + ".xlsx"
      );
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.configOptions = response.data;
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.typeName,
        children: node.children,
      };
    },
  },
};
</script>
